// 商品详情页逻辑
Page({
  data: {
    productId: null,
    product: {},
    productImages: [],
    currentImageIndex: 0,
    groupMode: 'traditional', // traditional, lottery
    countdown: '',
    currentParticipants: 0,
    participationProgress: 0,
    participantAvatars: [],
    relatedProducts: [],
    latestReviews: [],
    reviewCount: 0,
    ratingStats: [],
    isFavorited: false,
    showSpecModal: false,
    quantity: 1,
    productSpecs: [],
    selectedSpecs: {},
    isScrollTop: true,
    selectedSpecsText: '请选择规格'
  },

  onLoad(options) {
    this.data.productId = options.id || options.productId;
    this.loadProductDetail();
    this.showShareFrom(options.shareFrom);
  },

  onShow() {
    this.startCountdown();
  },

  onHide() {
    this.stopCountdown();
  },

  onUnload() {
    this.stopCountdown();
  },

  // 显示分享来源
  showShareFrom(shareFrom) {
    if (shareFrom === 'home') {
      wx.showToast({
        title: '来自首页分享',
        icon: 'none'
      });
    }
  },

  // 加载商品详情
  async loadProductDetail() {
    wx.showLoading({
      title: '加载中...',
    });

    try {
      // 模拟商品数据
      const product = this.generateMockProduct();

      this.setData({
        product,
        productImages: product.images,
        currentParticipants: product.currentParticipants || 0,
        participationProgress: product.participationProgress || 0,
        participantAvatars: product.participantAvatars || [],
        isFavorited: product.isFavorited || false,
        productSpecs: product.specs || []
      });

      this.loadRelatedProducts();
      this.loadProductReviews();
      this.updateProgressBar();

    } catch (error) {
      console.error('加载商品详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 生成模拟商品数据
  generateMockProduct() {
    const specs = [
      {
        name: '颜色',
        options: [
          { value: '红色', selected: false },
          { value: '蓝色', selected: false },
          { value: '黑色', selected: true }
        ]
      },
      {
        name: '尺码',
        options: [
          { value: 'S', selected: true },
          { value: 'M', selected: false },
          { value: 'L', selected: false },
          { value: 'XL', selected: false }
        ]
      }
    ];

    const images = [
      '/images/product-detail1.jpg',
      '/images/product-detail2.jpg',
      '/images/product-detail3.jpg',
      '/images/product-detail4.jpg',
      '/images/product-detail5.jpg'
    ];

    this.updateSelectedSpecsText(specs);

    return {
      id: this.data.productId,
      title: '高品质智能蓝牙耳机 无线降噪运动耳机',
      subtitle: '智能降噪技术，超长续航，舒适佩戴',
      images: images,
      groupPriceInteger: '299',
      groupPriceDecimal: '00',
      originalPrice: 599,
      discount: '5.0',
      stock: 100,
      targetCount: 10,
      currentParticipants: 6,
      participationProgress: 60,
      participantAvatars: [
        '/images/avatar1.jpg',
        '/images/avatar2.jpg',
        '/images/avatar3.jpg',
        '/images/avatar4.jpg',
        '/images/avatar5.jpg'
      ],
      activityHours: 72,
      expireAction: '到期未成团将自动退款',
      depositRate: 25, // 25%
      winnerCount: 2,
      consolationPrize: 10,
      specs: specs,
      detailContent: [
        {
          type: 'text',
          content: '高品质智能蓝牙耳机，采用最新蓝牙5.0技术，连接稳定，音质清晰。'
        },
        {
          type: 'image',
          src: '/images/product-desc1.jpg'
        },
        {
          type: 'text',
          content: '智能降噪技术，有效隔绝外界噪音，让您享受纯净的音乐体验。'
        },
        {
          type: 'image',
          src: '/images/product-desc2.jpg'
        }
      ],
      hasSpecs: true,
      isFavorited: false,
      rating: 4.8,
      reviewCount: 128
    };
  },

  // 更新选中规格文本
  updateSelectedSpecsText(specs) {
    if (!specs || specs.length === 0) return;

    const selectedValues = [];
    specs.forEach(spec => {
      const selected = spec.options.find(option => option.selected);
      if (selected) {
        selectedValues.push(selected.value);
      }
    });

    this.setData({
      selectedSpecsText: selectedValues.length > 0 ? selectedValues.join(', ') : '请选择规格'
    });
  },

  // 切换团购模式
  switchGroupMode(e) {
    const mode = e.currentTarget.dataset.mode;
    if (this.data.groupMode === mode) return;

    this.setData({
      groupMode: mode
    });

    // 如果有相应的模式数据，重新加载参与情况
    this.updateParticipationData();
  },

  // 更新参与数据
  updateParticipationData() {
    // 模拟不同模式的参与数据
    if (this.data.groupMode === 'lottery') {
      this.setData({
        currentParticipants: 15,
        participationProgress: 30  // 15/50
      });
    } else {
      this.setData({
        currentParticipants: 6,
        participationProgress: 60  // 6/10
      });
    }
  },

  // 更新进度条
  updateProgressBar() {
    const current = this.data.currentParticipants;
    const target = this.data.product.targetCount;
    const progress = Math.floor((current / target) * 100);

    this.setData({
      participationProgress: progress
    });
  },

  // 加载相关商品
  async loadRelatedProducts() {
    // 模拟相关商品数据
    const relatedProducts = [
      {
        id: 1001,
        title: '无线充电器',
        price: 99,
        image: '/images/related1.jpg'
      },
      {
        id: 1002,
        title: '手机支架',
        price: 59,
        image: '/images/related2.jpg'
      },
      {
        id: 1003,
        title: '充电宝',
        price: 129,
        image: '/images/related3.jpg'
      },
      {
        id: 1004,
        title: '数据线',
        price: 39,
        image: '/images/related4.jpg'
      }
    ];

    this.setData({
      relatedProducts
    });
  },

  // 加载商品评价
  async loadProductReviews() {
    // 模拟评价数据
    const ratingStats = [
      { label: '5星', percent: 75, count: 96 },
      { label: '4星', percent: 20, count: 26 },
      { label: '3星', percent: 4, count: 5 },
      { label: '2星', percent: 1, count: 1 },
      { label: '1星', percent: 0, count: 0 }
    ];

    const latestReviews = [
      {
        id: 1,
        avatar: '/images/reviewer1.jpg',
        name: '张***',
        rating: 5,
        date: '2024-01-15',
        content: '音质很好，降噪效果明显，佩戴舒适，性价比高！',
        images: ['/images/review1-1.jpg', '/images/review1-2.jpg']
      },
      {
        id: 2,
        avatar: '/images/reviewer2.jpg',
        name: '李***',
        rating: 5,
        date: '2024-01-14',
        content: '外观时尚，连接稳定，音质清晰，值得购买。',
        images: []
      },
      {
        id: 3,
        avatar: '/images/reviewer3.jpg',
        name: '王***',
        rating: 4,
        date: '2024-01-13',
        content: '整体不错，续航能力还可以再提升。',
        images: ['/images/review3-1.jpg']
      }
    ];

    this.setData({
      ratingStats,
      latestReviews
    });
  },

  // 开始倒计时
  startCountdown() {
    this.updateCountdown();
    this.countdownTimer = setInterval(() => {
      this.updateCountdown();
    }, 1000);
  },

  // 停止倒计时
  stopCountdown() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer);
      this.countdownTimer = null;
    }
  },

  // 更新倒计时
  updateCountdown() {
    // 模拟倒计时
    const endTime = new Date().getTime() + 60 * 60 * 72 * 1000; // 72小时后
    const now = new Date().getTime();
    const remaining = endTime - now;

    if (remaining <= 0) {
      this.setData({
        countdown: '00:00:00'
      });
      this.stopCountdown();
      return;
    }

    const hours = Math.floor(remaining / (1000 * 60 * 60));
    const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((remaining % (1000 * 60)) / 1000);

    this.setData({
      countdown: `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    });
  },

  // 切换收藏状态
  toggleFavorite() {
    this.setData({
      isFavorited: !this.data.isFavorited
    });

    wx.showToast({
      title: this.data.isFavorited ? '已收藏' : '取消收藏',
      icon: 'success'
    });
  },

  // 预览图片
  previewImage(e) {
    const src = e.currentTarget.dataset.src;
    wx.previewImage({
      current: src,
      urls: this.data.productImages
    });
  },

  // 预览评价图片
  previewReviewImage(e) {
    const src = e.currentTarget.dataset.src;
    const images = e.currentTarget.dataset.images;
    wx.previewImage({
      current: src,
      urls: images
    });
  },

  // 显示规格选择
  showSpecModal() {
    this.setData({
      showSpecModal: true
    });
  },

  // 隐藏规格选择
  hideSpecModal() {
    this.setData({
      showSpecModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 防止点击modal内容时关闭弹窗
  },

  // 选择规格
  selectSpec(e) {
    const { group, value } = e.currentTarget.dataset;
    const specs = this.data.productSpecs.map(specGroup => {
      if (specGroup.name === group) {
        return {
          ...specGroup,
          options: specGroup.options.map(option => ({
            ...option,
            selected: option.value === value
          }))
        };
      }
      return specGroup;
    });

    this.setData({
      productSpecs: specs
    });

    this.updateSelectedSpecsText(specs);
  },

  // 减少数量
  reduceQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      });
    }
  },

  // 增加数量
  addQuantity() {
    const stock = this.data.product.stock || 100;
    if (this.data.quantity < stock) {
      this.setData({
        quantity: this.data.quantity + 1
      });
    }
  },

  // 确认规格选择
  confirmSpec() {
    // 验证是否选择了所有必需的规格
    const specs = this.data.productSpecs;
    const hasUnselected = specs.some(specGroup =>
      !specGroup.options.some(option => option.selected)
    );

    if (hasUnselected) {
      wx.showToast({
        title: '请选择所有规格',
        icon: 'none'
      });
      return;
    }

    this.hideSpecModal();

    // 如果需要立即参团，可以在这里调用参团逻辑
    if (this.data.showJoinModal) {
      this.joinGroup();
    }
  },

  // 显示参团弹窗
  showJoinModal() {
    if (!this.data.product.hasSpecs) {
      this.joinGroup();
      return;
    }

    this.setData({
      showJoinModal: true
    });
    this.showSpecModal();
  },

  // 参与团购
  joinGroup() {
    // 验证是否选择了规格
    if (!this.validateSpecSelection()) {
      this.showSpecModal();
      return;
    }

    const groupType = this.data.groupMode;
    const product = this.data.product;

    if (groupType === 'lottery') {
      // 抽奖团购
      const deposit = Math.floor(product.groupPrice * 0.25);
      wx.showModal({
        title: '参与抽奖团购',
        content: `支付定金¥${deposit}参与抽奖，${product.winnerCount}个中奖名额，未中奖获得${product.consolationPrize}元安慰券`,
        confirmText: '支付定金',
        success: (res) => {
          if (res.confirm) {
            this.goToPayment('lottery', deposit);
          }
        }
      });
    } else {
      // 普通团购
      this.goToPayment('traditional', product.groupPrice);
    }
  },

  // 验证规格选择
  validateSpecSelection() {
    if (!this.data.product.hasSpecs) return true;

    const specs = this.data.productSpecs;
    return specs.every(specGroup =>
      specGroup.options.some(option => option.selected)
    );
  },

  // 前往支付页面
  goToPayment(groupType, amount) {
    const params = {
      productId: this.data.productId,
      groupType: groupType,
      amount: amount,
      quantity: this.data.quantity,
      specs: JSON.stringify(this.data.selectedSpecs)
    };

    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&');

    wx.navigateTo({
      url: `/pages/payment/index?${queryString}`
    });
  },

  // 跳转到其他商品
  goToProduct(e) {
    const id = e.currentTarget.dataset.id;
    wx.redirectTo({
      url: `/pages/product/detail?id=${id}`
    });
  },

  // 联系客服
  contactService() {
    wx.showModal({
      title: '联系客服',
      content: '客服电话: 400-123-4567\n工作时间: 9:00-22:00',
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '4001234567'
          });
        }
      }
    });
  },

  // 页面滚动事件
  onPageScroll(e) {
    const isScrollTop = e.scrollTop <= 50;
    if (this.data.isScrollTop !== isScrollTop) {
      this.setData({
        isScrollTop
      });
    }
  },

  // 页面分享
  onShareAppMessage() {
    const product = this.data.product;
    return {
      title: `我发现了一个超值${this.data.groupMode === 'lottery' ? '抽奖' : '团购'}：${product.title}`,
      path: `/pages/product/detail?id=${product.id}&shareFrom=detail`,
      imageUrl: product.images[0]
    };
  }
});